package com.jp.knowledge.logic;

import android.content.Context;
import android.content.DialogInterface;
import android.content.Intent;
import android.os.Handler;
import android.support.v4.content.LocalBroadcastManager;

import com.google.gson.JsonObject;
import com.jiayen.cache.FileCacheManager;
import com.jp.knowledge.broad.LocalBroadCast;
import com.jp.knowledge.db.DBHelper;
import com.jp.knowledge.dialog.ComPopuWindow;
import com.jp.knowledge.dialog.HeadlineDragDialog;
import com.jp.knowledge.fragment.PositionKnowleageFragment;
import com.jp.knowledge.http.HttpHelper;
import com.jp.knowledge.model.HeadLine;
import com.jp.knowledge.model.IModel;
import com.jp.knowledge.model.PositionKnowlegeMode;
import com.jp.knowledge.util.JsonUtil;
import com.jp.knowledge.util.ResultSubscriber;

import java.util.ArrayList;
import java.util.List;

import rx.Observable;
import rx.Subscriber;
import rx.android.schedulers.AndroidSchedulers;
import rx.schedulers.Schedulers;

/**
 * Created by jiayen on 17/6/14.
 *
 * 拖动逻辑书写
 */

public class DragLogic implements ResultSubscriber.OnResultListener {

    private Context mContext;
    private HeadlineDragDialog dragDialog;
    private FileCacheManager fileCacheManager;
    private List<PositionKnowlegeMode> models;

    private  List<HeadLine> headLines;

    private Handler handler = new Handler();
    private LocalBroadcastManager  localBroadcastManager;
    private PositionKnowlegeDataLogic  dataLogic;
    public DragLogic(Context context){
            this.mContext=context;
        dataLogic = PositionKnowlegeDataLogic.getInstance(mContext);

        dataLogic.setCallkBack(new PositionKnowlegeDataLogic.SucdessCallkBack() {
            @Override
            public void done(List<PositionKnowlegeMode> mdls) {
                    models=mdls;
                setView();
            }
        });
        localBroadcastManager = LocalBroadcastManager.getInstance(mContext);
        fileCacheManager = new FileCacheManager();
        initDrag();
        getPositionData();
    }
    public void initDrag(){
        dragDialog = new HeadlineDragDialog(mContext);
        dragDialog.setDragItemHelper(new ComPopuWindow.DragItemHelper() {
            @Override
            public void drag(int fromPositon, int toPosition) {
                final int toP = toPosition;
                //排序数据
                if(models!=null) {
                    PositionKnowlegeMode headLine = models.remove(fromPositon);
                    models.add(toPosition, headLine);
                }

//                handler.postDelayed(new Runnable() {
//                    @Override
//                    public void run() {
//                        handler.sendEmptyMessage(toP);
//                    }
//                },800);

//

            }

            @Override
            public void dragFinish() {

            }
        });

        dragDialog.setOnDismissListener(new DialogInterface.OnDismissListener() {
            @Override
            public void onDismiss(DialogInterface dialog) {//保存排序后的缓存
                saveCache(models,getCachePath());
                DBHelper.getInstance().delete(HeadLine.class);
                DBHelper.getInstance().save(headLines);
                JsonObject param = new JsonObject();
                param.addProperty("data", JsonUtil.getInstance().objToJson(headLines));
                //更新服务端的顺序
                HttpHelper.getInstance(mContext).headLineUpdate(param, 0x00000016, DragLogic.this);
                handler.postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        Intent intent = new Intent();
                        intent.setAction(LocalBroadCast.HEAD_LINE_SORT);
                        localBroadcastManager.sendBroadcast(intent);
                    }
                },10);

            }
        });
    }

    public void showDragDaiog(){
        dragDialog.show();
    }



    /***
     * 获取岗位知识数据
     */
    private void getPositionData(){
        models = PositionKnowlegeDataLogic.getModels();
        if(models==null||models.size()==0){
            Observable.create(new Observable.OnSubscribe<List<PositionKnowlegeMode>>() {
                @Override
                public void call(Subscriber<? super List<PositionKnowlegeMode>> subscriber) {
                    try {
                        List<PositionKnowlegeMode> data = (List<PositionKnowlegeMode>) fileCacheManager.readObject(getCachePath());
                        subscriber.onNext(data);
                    }catch (Exception e){

                    }
                }
            }).subscribeOn(Schedulers.io())
                    .observeOn(AndroidSchedulers.mainThread())
                    .subscribe(new Subscriber<List<PositionKnowlegeMode>>() {
                        @Override
                        public void onCompleted() {
                        }
                        @Override
                        public void onError(Throwable e) {
                            onCompleted();
                        }
                        @Override
                        public void onNext(List<PositionKnowlegeMode> data) {
                            models = data;
                            if(models == null ||models.size()==0) {//|| System.currentTimeMillis()-skillModel.getCacheTime() > 1000*60*10
                                      dataLogic.getKnowlegeData();
                            }else{
                                PositionKnowlegeDataLogic.setModels(models);
                                setView();
                            }
                        }
                    });
        }else{
                dataLogic.getKnowlegeData();
        }
    }
    private void setView() {

        if(models!=null){
            headLines = new ArrayList<>();
            for (PositionKnowlegeMode model: models) {
                HeadLine hedLine = new HeadLine();
                hedLine.setTypeName(model.getName());
                hedLine.setTypeId(model.getNavType());
                headLines.add(hedLine);
            }
            dragDialog.updateData(headLines);
        }

    }

    private String getCachePath(){
        return mContext.getCacheDir() + "/skillCache_position_knowlege_all"  + ".dat";
    }
    private void saveCache(final Object data, final String path){
        new Thread(new Runnable() {
            @Override
            public void run() {
                fileCacheManager.wirteObject(data, path);
            }
        }).start();
    }

    @Override
    public void onStart(int requestType) {

    }

    @Override
    public void onCompleted(int requestType) {

    }

    @Override
    public void onError(int requestType) {

    }

    @Override
    public void onNext(IModel data, int requestType) {
            if(data.getErrcode()==0){
                if(requestType==1){
                    headLines = data.getList(HeadLine.class);
                    update();
                }
            }
    }

    private void update(){
            dragDialog.updateData(headLines);
    }

}
